package com.demo.youxuanmall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.demo.youxuanmall.common.Result;
import com.demo.youxuanmall.entity.Category;
import com.demo.youxuanmall.entity.Order;
import com.demo.youxuanmall.entity.Product;
import com.demo.youxuanmall.entity.User;
import com.demo.youxuanmall.mapper.CategoryMapper;
import com.demo.youxuanmall.mapper.OrderMapper;
import com.demo.youxuanmall.mapper.ProductMapper;
import com.demo.youxuanmall.mapper.UserMapper;
import com.demo.youxuanmall.service.StatisticsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class StatisticsServiceImpl implements StatisticsService {

    private final UserMapper userMapper;
    private final ProductMapper productMapper;
    private final OrderMapper orderMapper;
    private final CategoryMapper categoryMapper;

    @Override
    public Result<Map<String, Object>> getOverviewStats() {
        try {
            Map<String, Object> data = new HashMap<>();
            
            // 用户统计
            Integer totalUsers = userMapper.getTotalUserCount();
            
            // 商品统计
            Long totalProducts = productMapper.selectCount(null);
            
            // 订单统计
            Long totalOrders = orderMapper.selectCount(null);
            
            // 销售额统计
            BigDecimal totalSales = orderMapper.getTotalSales();
            
            data.put("totalUsers", totalUsers);
            data.put("totalProducts", totalProducts);
            data.put("totalOrders", totalOrders);
            data.put("totalSales", totalSales != null ? totalSales : BigDecimal.ZERO);
            
            return Result.success(data);
        } catch (Exception e) {
            log.error("获取概览统计数据出错", e);
            return Result.error("获取统计数据失败：" + e.getMessage());
        }
    }

    @Override
    public Result<Map<String, Object>> getSalesTrend(Integer days) {
        try {
            // 获取开始和结束日期
            LocalDate endDate = LocalDate.now();
            LocalDate startDate = endDate.minusDays(days);
            
            // 查询每天的销售额
            List<Map<String, Object>> salesData = orderMapper.getSalesTrendByDay(
                    startDate.format(DateTimeFormatter.ISO_DATE),
                    endDate.format(DateTimeFormatter.ISO_DATE)
            );
            
            // 组装结果数据
            Map<String, Object> result = new HashMap<>();
            result.put("salesData", salesData);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取销售趋势数据出错", e);
            return Result.error("获取销售趋势失败：" + e.getMessage());
        }
    }

    @Override
    public Result<Map<String, Integer>> getOrderStatusDistribution() {
        try {
            // 统计各状态订单数量
            Map<String, Integer> statusCounts = new HashMap<>();
            
            // 待付款订单数
            Integer pendingPayment = orderMapper.countOrdersByStatus(0);
            statusCounts.put("pendingPayment", pendingPayment);
            
            // 待发货订单数
            Integer pendingShipment = orderMapper.countOrdersByStatus(1);
            statusCounts.put("pendingShipment", pendingShipment);
            
            // 待收货订单数
            Integer shipped = orderMapper.countOrdersByStatus(2);
            statusCounts.put("shipped", shipped);
            
            // 已完成订单数
            Integer completed = orderMapper.countOrdersByStatus(3);
            statusCounts.put("completed", completed);
            
            // 已取消订单数
            Integer cancelled = orderMapper.countOrdersByStatus(4);
            statusCounts.put("cancelled", cancelled);
            
            return Result.success(statusCounts);
        } catch (Exception e) {
            log.error("获取订单状态分布数据出错", e);
            return Result.error("获取订单状态分布失败：" + e.getMessage());
        }
    }

    @Override
    public Result<List<Map<String, Object>>> getCategorySalesPercentage() {
        try {
            // 获取各分类销售占比
            List<Map<String, Object>> categorySales = orderMapper.getCategorySalesPercentage();
            
            return Result.success(categorySales);
        } catch (Exception e) {
            log.error("获取分类销售占比数据出错", e);
            return Result.error("获取分类销售占比失败：" + e.getMessage());
        }
    }

    @Override
    public Result<List<Map<String, Object>>> getHotProducts(Integer limit) {
        try {
            // 获取热门商品
            List<Map<String, Object>> hotProducts = orderMapper.getHotProducts(limit);
            
            return Result.success(hotProducts);
        } catch (Exception e) {
            log.error("获取热门商品数据出错", e);
            return Result.error("获取热门商品失败：" + e.getMessage());
        }
    }

    @Override
    public Result<Map<String, Object>> getUserGrowth(Integer days) {
        try {
            // 获取开始和结束日期
            LocalDate endDate = LocalDate.now();
            LocalDate startDate = endDate.minusDays(days);
            
            // 获取用户增长数据
            List<Map<String, Object>> userGrowthData = userMapper.getUserGrowthByDay(
                    startDate.format(DateTimeFormatter.ISO_DATE),
                    endDate.format(DateTimeFormatter.ISO_DATE)
            );
            
            // 总用户数
            Integer totalUsers = userMapper.getTotalUserCount();
            
            // 组装结果
            Map<String, Object> result = new HashMap<>();
            result.put("userGrowthData", userGrowthData);
            result.put("totalUsers", totalUsers);
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取用户增长数据出错", e);
            return Result.error("获取用户增长数据失败：" + e.getMessage());
        }
    }
} 